<?php
// +----------------------------------------------------------------------
// | 通用PHP框架 [ ThinkPHP ]
// +----------------------------------------------------------------------
// | 版权所有 2016~2019 郑州智众 [Paulxun@qq.com]
// +----------------------------------------------------------------------
// | 官方网站: https://www.zzmind.com
// +----------------------------------------------------------------------

namespace app\user\admin;

use app\admin\controller\Admin;
use app\common\builder\ZBuilder;
use app\mall\model\Order as OrderModel;
use app\user\model\Member as MemberModel;
use app\user\model\Vip as VipModel;
use app\user\model\Money as MoneyModel;
use app\user\model\Rebate as RebateModel;
use app\user\model\Level;
use util\Tree;
use think\facade\Db;

/**
 * Vip会员管理控制器
 * @package app\user\admin
 */
class Vip extends Admin
{
    /**
     * 用户首页
     * @author PaulXun <paulxun@qq.com>
     * @return mixed
     * @throws \think\Exception
     * @throws \think\exception\DbException
     */
    public function index($uid = 0)
    {
        cookie('__forward__', $_SERVER['REQUEST_URI']);

        // 获取查询条件
        $map = $this->getMap();

        if ($uid > 0) {
            $map[] = ['user_vip.member_id', '=', $uid];
            $search_field = [];
        } else {
            $search_field = ['member_id' => '会员ID', 'user_member.nickname' => '昵称', 'user_vip.realname' => '姓名', 'user_vip.mobile' => '手机号'];
        }
        // 排序条件
        $order = $this->getOrder('member_id asc');

        // 数据列表
        $data_list = VipModel::getList($map, $order);
        // 充值按钮
        $btn_access = [
            'title' => '充值',
            'icon'  => 'fa fa-fw fa-cny',
            'class' => 'btn btn-xs btn-primary',
            'href'  => url('pay', ['id' => '__id__'])
        ];
        // 导出按钮
        $btnExport = [
            'title' => '导出资料',
            'icon'  => 'fa fa-fw fa-file-excel-o',
            'class' => 'btn btn-primary',
            'href'  => url('export')
        ];
        // 使用ZBuilder快速创建数据表格
        return ZBuilder::make('table')
            ->setPageTitle('Vip管理') // 设置页面标题
            ->setSearch($search_field) // 设置搜索参数
            ->addColumns([ // 批量添加列
                ['member_id', '会员ID'],
                // ['openid', '微信OPENID'],
                ['realname', '姓名'],
                ['mobile', '手机号'],
                ['nickname', '昵称'],
                ['pid', '团队', 'callback', function($value, $data){ $info = VipModel::info($value); if($info['realname'] == '') $info['realname'] = '公司直属'; return $info['realname'].'<br/><a class="btn btn-xs btn-primary pop" href="'.url('group', ['pid' => $data['pid']]) .'&_pop=1">Ta的团队</a>';}, '__data__'],
                ['group', '会员等级', 'callback', function($value){return Level::level_list($value);}],
                ['policy', '政策类型', 'callback', function($value){return Level::policy_list($value);}],
                ['agent', '代理类型', 'callback', function($value){return Level::agent_list($value);}],
                ['shop', '店铺类型', 'callback', function($value){return Level::shop_list($value);}],
                ['money', '余额', 'callback', function($value){return '￥'. $value / 100 ;}],
//                ['money_se', '补货余额', 'callback', function($value, $data){return '￥'. $value / 100 .'<br/><a class="btn btn-xs btn-primary pop" href="'.url('money/index', ['uid' => $data['member_id']]) .'&_pop=1">资金变动</a>';}, '__data__'],
                ['money_take', '可提现余额', 'callback', function($value, $data){return '￥'. $value / 100 .'<br/><a class="btn btn-xs btn-primary pop" href="'.url('rebate/index', ['uid' => $data['member_id']]) .'&_pop=1">返佣记录</a>';}, '__data__'],
                ['create_time', '认证时间', 'datetime'],
                ['edit_address', '允许修改地址', 'switch'],
                ['status', '状态', 'switch'],
                ['old', '来源', 'status', '', ['新用户', '老用户']],
                ['right_button', '操作', 'btn']
            ])
            ->addTopButtons('enable,disable,delete') // 批量添加顶部按钮
            ->addTopButton('custom', $btnExport, true) // 添加导出按钮
            ->addRightButton('custom', $btn_access, true)
            ->addRightButtons('edit,delete') // 批量添加右侧按钮
            ->setRowList($data_list) // 设置表格数据
            ->addFilterList('group', Level::level_list())
            ->addFilterList('shop', Level::shop_list())
            ->addFilterList('old', ['新用户', '老用户'])
            // ->setColumnWidth(['money' => 160, 'pay_time' => 80])
            ->setPrimaryKey('member_id') // 设置主键名为member_id
            ->fetch(); // 渲染页面
    }
    /**
     * 用户层级列表页
     * @author PaulXun <paulxun@qq.com>
     * @return mixed
     * @throws \think\Exception
     * @throws \think\exception\DbException
     */
    public function group($pid = 0)
    {
        cookie('__forward__', $_SERVER['REQUEST_URI']);

        // 获取查询条件
        $map = $this->getMap();

        if($pid>0){
            $map[] = ['pid', '=', $pid];
            $map[] = ['group', '>', 0];
        }else{
            $key = input('param.keyword/s', '', 'trim');
            if($key!=""){
                $map[] = ['mobile', '=', $key];
            }
            $map[] = ['group', '>', 0];
            $map[] = ['pid', '=', $pid];
        }
        $order = $this->getOrder('member_id asc');
        //查询销量冠军
        $month_start = strtotime(date("Y-m-01"));
        $month_end = strtotime("+1 month -1 seconds", $month_start);

        // 数据列表

        // $map[] = ['status', '=', 1];
        $data_list = VipModel::where($map)->order($order)->select();
        if ($data_list) {
            // 用户组列表
            $group_list = Level::level_list();
            $shop_list = Level::shop_list();
            $team_list[0] = '无';
            $return_list = [];
            foreach ($data_list as $key => $value){
                $ids = VipModel::getChilds($value['member_id']);
                $count_map = [
                    ['pay_time', 'between', [$month_start, $month_end]],
                    ['uid', 'in', $ids],
                ];
                $oids = OrderModel::where($count_map)->column('id');
                $map = [
                    ['oid', 'in', $oids],
                ];
                $count_list = Db::name('mall_order_detail')->where($map)->field('sum(balance) as balance, sum(second) as second, sum(realpay) as realpay, sum(number) as number, sum(pay_price) as pay_price, sum(number) as total')->find();

                $count = count(VipModel::getChilds($value['member_id']));
                $name = '团队人数';
                $return_list[$key] = [
                    'label' => $value['realname'],
                    'id'	=> $value['member_id'],
                    'mobile'=> $value['mobile'],
                    'shop'	=> $shop_list[$value['shop']],
                    'group'	=> $group_list[$value['group']],
                    'pay_price'	=> $count_list['pay_price'],
                    'count'	=> $count,
                    'team_no'	=> $name,
                    'url'	=> admin_url('user/vip/index', ['uid' => $value['member_id']]),
                ];
            }
        }else{
            $return_list = [];
        }
        if (request()->isAjax()){
            if ($return_list) {
                $this->success('请求成功', '', $return_list);
            }else{
                $this->error('暂无数据！');
            }
        }
        $this->assign('list', $return_list);
        // 使用ZBuilder快速创建数据表格
//        return ZBuilder::make('table')
//            ->setPageTitle('Vip管理') // 设置页面标题
//            ->setSearch($search_field) // 设置搜索参数
//            ->addColumns([ // 批量添加列
//                ['uid', '会员ID'],
//                ['realname', '姓名'],
//                ['mobile', '手机号'],
//                ['group', '会员等级', 'callback', function($value){return Level::level_list($value);}],
//
//            ])
//            ->setRowList($return_list) // 设置表格数据
//            ->fetch();
        return $this->fetch(); // 渲染页面
    }

    /**
     * 整体团队页
     * @author PaulXun <paulxun@qq.com>
     * @return mixed
     * @throws \think\Exception
     * @throws \think\exception\DbException
     */
    public function team($pid = 0)
    {
        cookie('__forward__', $_SERVER['REQUEST_URI']);

        // 获取查询条件
        $map = $this->getMap();
        $order = $this->getOrder('member_id asc');

        // 数据列表
        $map[] = ['pid', '=', $pid];
        $map[] = ['group', '>', 0];
        // $map[] = ['status', '=', 1];
        $data_list = VipModel::where($map)->order($order)->select();
        if ($data_list) {
            // 用户组列表
            $group_list = Level::level_list();
            $shop_list = Level::shop_list();
            $team_list[0] = '无';
            $return_list = [];
            foreach ($data_list as $key => $value){
                $count = count(VipModel::getChilds($value['member_id']));
                $name = '团队人数';
                $return_list[$key] = [
                    'label' => $value['realname'],
                    'id'	=> $value['member_id'],
                    'mobile'=> $value['mobile'],
                    'shop'	=> $shop_list[$value['shop']],
                    'group'	=> $group_list[$value['group']],
                    'count'	=> $count,
                    'team_no'	=> $name,
                    'url'	=> admin_url('user/vip/index', ['uid' => $value['member_id']]),
                ];
            }
        }else{
            $return_list = [];
        }
        if (request()->isAjax()){
            if ($return_list) {
                $this->success('请求成功', '', $return_list);
            }else{
                $this->error('暂无数据！');
            }
        }
        $this->assign('list', $return_list);
        // 使用ZBuilder快速创建数据表格
        return $this->fetch(); // 渲染页面
    }
    /**
     * 编辑
     * @param null $id 用户id
     * @author PaulXun <paulxun@qq.com>
     * @return mixed
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function edit($id = null)
    {
        if ($id === null) $this->error('缺少参数');
        // 获取自己的后代ID
        $ids = VipModel::getChildsId($id);
        $ids[] = $id;
        //获取列表
        $pluser = VipModel::where('member_id', 'not in', $ids)->where('status', '=', 1)->where('group', '>', 1)->column('realname', 'member_id');

        // 获取数据
        $info = VipModel::where('member_id', $id)->find();
        $info['money'] = $info['money'] / 100 ;
//        $info['money_se'] = $info['money_se'] / 100 ;
        $info['money_take'] = $info['money_take'] / 100 ;

        // 保存数据
        if ($this->request->isPost()) {
            $data = $this->request->post();

            unset($data['__token__']);
            // 验证
            $result = $this->validate($data, 'Vip');

            // 验证失败 输出错误信息
            if(true !== $result) $this->error($result);
            // 检查Vip信息
            if ($data['pid'] > 0) {
                if (in_array($data['pid'], $ids)) {
                    $this->error('推荐人在你的团队里, 不能互推！');
                }
                // 同步到会员表
                if ($data['pid'] != $info['pid']) {
                    MemberModel::where('id', $id)->update(['pid' => $data['pid']]);
                }
            }

            if (VipModel::where('member_id', '=', $data['member_id'])->update($data)) {
                cache('vip_'.$id, null);
                // 记录行为
                action_log('member_edit', 'user_vip', $data['member_id'], UID, $data['realname']);
                $group = Level::level_list($data['group']);

                if($data['group'] != $info['group']){
                    $MemberModel = new MemberModel;
                    $user = $MemberModel::where('id',$data['member_id'])->where('status', 1)->find();

                    $sendData = [
                        'template_id'   => '6iCuLOFSHI4rSLNEbgcE8TJ9EVU6kfEZwrHwNSr51Y8',//模板消息ID
                        'touser'    => $user['openid'],//用户openid
                        'data'=>[
                            'first'=>[
                                'value'=>'亲，让你久等了!',
                                'color'=>'#000000',
                            ],
                            'keyword1'=>[
                                'value'=>$group,//订单编号
                                'color'=>'#000000'
                            ],
                            'keyword2'=>[
                                'value'=>'升级成功！',//审核状态
                                'color'=>'#000000'
                            ],
                            'remark'=>[
                                'value'=>'大白家，祝您步步高升！！',//描述
                                'color'=>'#173177',
                            ],
                        ]
                    ];
                    $this->template($sendData);
                }
                $this->success('编辑成功', cookie('__forward__'));
            } else {
                $this->error('编辑失败');
            }
        }
        $pluser[0] = '顶级';
        // 重设可选推荐人列表
        foreach ($pluser as $key => $value) {
            $pluser[$key] = $value.'(id'.$key.')';
        }
        // 等级列表
        $level_list = Level::level_list();
        $agent_list = level::agent_list();
        $policy_list = Level::policy_list();

        // 使用ZBuilder快速创建表单
        return ZBuilder::make('form')
            ->setPageTitle('编辑') // 设置页面标题
            ->addFormItems([ // 批量添加表单项
                ['hidden', 'member_id'],
                ['text', 'realname', '姓名'],
                ['text', 'mobile', '手机号'],
                ['text', 'idcard', '身份证号', ''],
                ['select', 'pid', '推荐人', '', $pluser],
                ['static', 'money', '首单余额', '单位：元'],
//                ['static', 'money_se', '补货余额', '单位：元'],
                ['static', 'money_take', '返佣余额', '单位：元'],
                ['select', 'group', '会员等级', '', $level_list],
                ['select', 'agent', '代理类型', '', $agent_list],
                ['select', 'policy', '政策类型', '', $policy_list],
                ['select', 'shop', '店铺类型', '', Level::suffix('_shop')->column('name', 'id')],
                ['linkages', 'country', '选择地区', '', 'user_area', 3],
                ['text', 'address', '详细地址', ''],
                ['radio', 'auto_up', '是否自动升级', '', ['禁用', '启用']],
                ['radio', 'old', '是否老用户', '新用户强制首单余额拿货到￥19800，需商城同时配置生效', ['否', '是']],
                ['radio', 'status', '会员状态', '', ['禁用', '启用']]
            ])
            ->setFormData($info) // 设置表单数据
            ->fetch();
    }

    /**
     * 会员充值
     * @param null $id 用户id
     * @return mixed
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function pay($id = null)
    {
        if ($id === null) $this->error('缺少参数');

        // 保存数据
        if ($this->request->isPost()) {
            $data = $this->request->post();

            // 验证
            if(!is_numeric($data['pay']) || $data['pay'] == 0) $this->error('充值金额必须为非0数字');
            $money = 0;
            $money_se = 0;
            if ($data['type'] == 1) {
                $money = $data['pay'] * 100;
            } else {
                $money_se = $data['pay'] * 100;
            }
            $credit = MoneyModel::moneyLog($data['member_id'], 1, $money, $money_se, 0, $data['remark']);
            if ($credit !== false) {
                // if ($data['type'] == 1) {
                // 	// 处理返佣
                // 	$rebate = new RebateModel;
                // 	$rebate->saveData($id, 1, $data['type'], $data['pay'] * 100, $credit);
                // }
                // 记录行为
                $this->success('充值成功', null, '_close_pop');
            } else {
                $this->error($credit, null, '_close_pop');
            }
        }


        // 获取数据
        $info = VipModel::where('member_id', $id)->find();

        $info['money'] = $info['money'] / 100 ;
//        $info['money_se'] = $info['money_se'] / 100 ;
        // $user = new VipModel;
        // dd($user->getFathers($info['pid']));

        // 使用ZBuilder快速创建表单
        return ZBuilder::make('form')
            ->setPageTitle('编辑') // 设置页面标题
            ->addFormItems([ // 批量添加表单项
                ['hidden', 'member_id'],
                ['static', 'member_id', '会员ID', ''],
                ['static', 'realname', '真实姓名', ''],
                ['static', 'mobile', '手机号'],
                ['static', 'money', '余额', '单位：元'],
//                ['static', 'money_se', '补货余额', '单位：元'],
                ['text:8', 'pay', '充值金额', '','', ['<i class="fa fa-fw fa-yen"></i>', '元']],
                ['radio', 'type', '充值类型', '首单余额及补货余额，购买商品折扣不同，并将按照不同比例返点', [1 =>'首单余额', 2=>'补货余额'], 1],
                ['text:8', 'remark', '备注',]
            ])
            ->setFormData($info) // 设置表单数据
            ->fetch();
    }
    /**
     * 导出Vip资料
     * @param int $map 栏目id
     * @return mixed
     * @throws \think\Exception
     */
    public function export()
    {
        if(request()->isPost()){
            $data = request()->post();
            // 查询条件
            $map =[
                ['member_id', '>', 0],
            ];
            if($data['date1'] && $data['date2']) {
                $from = strtotime($data['date1']);
                $to = strtotime($data['date2']) + 3600*24 - 1;
                $map[] =['create_time', 'between', [$from, $to]];
            }
            if(!isset($data['group'])) $this->error('请选择会员等级');
            if($data['group'] != 99) $map[] =['group', '=', $data['group']];

            if(!isset($data['shop'])) $this->error('请选择店铺类型');
            if($data['shop'] != 99) $map[] =['shop', '=', $data['shop']];

            if(!isset($data['status'])) $this->error('请选择会员状态');
            if($data['status'] != 99) $map[] =['status', '=', $data['status']];

            if ($data['team'] > 0) {
                $ids = 	VipModel::getChildsId($data['team']);
                if (!$ids) $this->error('该团队暂无数据');
                $map[] =['member_id', 'in', $ids];
            }
            $return = [];
            // 排序条件
            $order = 'member_id';

            // 获取查询数据，数组形式
            $order_list =  VipModel::where($map)->order($order)->select();

            if(!$order_list) $this->error('该条件下无可导出数据');

            $order_list = $order_list->toArray();

            foreach ($order_list as $key => $value){
                $order_list[$key]['money'] = $value['money'] / 100;
//                $order_list[$key]['money_se'] = $value['money_se'] / 100;
                $order_list[$key]['money_take'] = $value['money_take'] / 100;
                $order_list[$key]['group'] = Level::level_list($value['group']);
                $order_list[$key]['shop'] = Level::shop_list($value['shop']);
                $order_list[$key]['agent'] = Level::agent_list($value['agent']);
                $order_list[$key]['policy'] = Level::policy_list($value['policy']);
                $order_list[$key]['time'] = format_time($value['create_time']);
                $order_list[$key]['status'] = $value['status'] == 0 ? '禁用' : '启用';
                $order_list[$key]['old'] = $value['old'] == 0 ? '新用户' : '老用户';
                $pusers  = 	VipModel::where('member_id',$value['pid'])->find();
                $order_list[$key]['p_realname'] = $pusers['realname'];
                $order_list[$key]['p_mobile'] = $pusers['mobile'];
                $order_list[$key]['p_group'] = Level::level_list($pusers['group']);
            }
            $return['list'] = $order_list;
            // 设置表头信息（对应字段名,显示表头名称）
            $head[0] = [
                'member_id'	=> '会员ID',
                'realname'	=> '姓名',
                'mobile'	=> '手机号',
                'idcard'	=> '身份证',
                'group'		=> '等级',
                'shop'		=> '店铺类型',
                'agent'		=> '代理类型',
                'policy'		=> '政策类型',
                'money' 	=> '余额',
//                'money_se'  => '补货余额',
                'money_take'=> '可提现余额',
                'status' 	=> '状态',
                'old' 	=> '来源',
                'time' 		=> '加入时间',
                'p_realname'	=> '推荐人姓名',
                'p_mobile'	=> '推荐人手机号',
                'p_group'		=> '推荐人等级',
            ];
            // 向第一行插入表头
            $return['list'] = array_merge($head, $return['list']);

            // 表格筛选字段
            $return['field'] = [];
            foreach ($head[0] as $key => $value){
                $return['field'][] = $key;
            }

            $return['title'] = '会员资料';
            // 返回数据（[导出文件名:title、字段信息:field、具体数据:list]）
            $this->success('导出成功', '', $return);
        }
        $js = <<<EOF
			<script type="text/javascript">
			$('input#date1').attr("autocomplete","off");
			$('input#date2').attr("autocomplete","off");
			</script>
EOF;
        // 设置表单
        return ZBuilder::make('form')
            ->setPageTips('请按需求选择数据筛选', 'info')
            ->setPageTitle('选择数据')
            ->addDaterange('date1,date2', '注册日期', '<span class="text-danger">注册日期的范围，可选</span>')
            ->addFormItems([
                ['radio', 'group', '会员等级', '', [99 => '全部'] + Level::level_list(), 99],

                ['radio', 'shop', '店铺类型', '', [99 => '全部'] + Level::suffix('_shop')->column('name', 'id'), 99],

                ['radio', 'status', '会员状态', '',[99 => '全部', 0 => '已禁用', 1 => '启用',], 99],
                ['text:8', 'team', '团队ID', '请输入团队长的会员ID，0为不限制', 0],
            ])
            ->layout(['ids' => 8, 'date1' => 8, 'date2' => 8])
            ->hideBtn(['submit', 'back'])
            ->addBtn('<button type="button" id="get_data" class="btn btn-info">导出资料</button>')
            ->js('js/excel,js/export') // 引入外部excel.js文件
            ->setExtraJs($js)
            ->fetch();
    }
    /**
     * 删除Vip用户
     * @param array $ids 用户id
     * @author PaulXun <paulxun@qq.com>
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function delete($ids = [])
    {
        return $this->setStatus('delete');
    }

    /**
     * 启用用户
     * @param array $ids 用户id
     * @author PaulXun <paulxun@qq.com>
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function enable($ids = [])
    {
        return $this->setStatus('enable');
    }

    /**
     * 禁用用户
     * @param array $ids 用户id
     * @author PaulXun <paulxun@qq.com>
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function disable($ids = [])
    {
        return $this->setStatus('disable');
    }

    /**
     * 设置产品状态：删除、禁用、启用
     * @param string $type 类型：enable/disable
     * @param array $record
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function setStatus($type = '', $record = [])
    {
        $ids        = $this->request->isPost() ? input('post.ids/a') : input('param.ids');
        $realname = VipModel::where('member_id', 'in', $ids)->column('realname');
        return parent::setStatus($type, ['vip_'.$type, 'user_vip', 0, UID, implode('、', $realname)]);
    }

    /**
     * 快速编辑
     * @param array $record 行为日志
     * @author PaulXun <paulxun@qq.com>
     * @return mixed
     */
    public function quickEdit($record = [])
    {
        $id      = input('post.pk', '');
        $field   = input('post.name', '');
        $value   = input('post.value', '');

        $config  = VipModel::where('member_id', $id)->value($field);
        cache('vip_'. $id, null);
        $details = '字段(' . $field . ')，原值(' . $config . ')，新值：(' . $value . ')';
        return parent::quickEdit(['vip_edit', 'user_vip', $id, UID, $details]);
    }
}
